DEBUG=no

ifeq ($(DEBUG),yes)
	CFLAGS=-Wall -g -O0 -I./include
	LDFLAGS=-g -O0
else
	CFLAGS=-O2 -Wall -I./include
	LDFLAGS=-O2
endif

TESTS=$(patsubst %.c,%,$(wildcard tests/*.c))
TESTNAMES=$(patsubst tests/%,%,$(TESTS))
SAMPLESRC=$(wildcard samples/*.c)
SAMPLES=$(patsubst samples/%.c,%.pthread,$(SAMPLESRC)) $(patsubst samples/%.c,%.thread,$(SAMPLESRC)) 

.PHONY:	all check

all:	libthread.so samples

samples:	$(SAMPLES)

libthread.so:	src/thread.o src/list.o
	$(CC) $(LDFLAGS) -shared -o $@ $^

src/thread.o:	src/thread.c
	$(CC) $(CFLAGS) -D__USE_VALGRIND -fPIC -o $@ -c $< -I./samples

src/list.o:	src/list.c
	$(CC) $(CFLAGS) -D__USE_VALGRIND -fPIC -o $@ -c $< -I./samples

%.pthread:	samples/%.c libthread.so
	$(CC) $(LDFLAGS) $(CFLAGS) -I./samples -D__USE_PTHREAD -o $@ $< -lpthread

%.thread:	samples/%.c libthread.so
	$(CC) $(LDFLAGS) $(CFLAGS) -I./samples -o $@ $< -L. -lthread

clean:
	rm -f libthread.so
	rm -f $(SAMPLES)
	rm -f $(TESTS)

check:	$(TESTS)
	@for i in $(TESTNAMES); do \
		echo "Testing $$i... \c"; \
		LD_LIBRARY_PATH=. ./tests/$$i || (echo " failed"; false) && echo "ok"; \
	done

memcheck: $(TESTS)
	@for i in $(TESTNAMES); do \
		echo "Testing $$i... "; \
		LD_LIBRARY_PATH=. valgrind --leak-check=full -q ./tests/$$i; \
	done

tests/%:	tests/%.c libthread.so
	$(CC) $(LDFLAGS) $(CFLAGS) -o $@ $< -L. -lthread
